//stdlib.cpp
#include "ostream.h"

namespace std
{
	void *__dso_handle;
	
	bool error = false;
	
	OStream cout;		//OStream cout
	OStreamError cerr;
	
	OStream& OStream::operator<<(char *cp)
	{
		write(cp) ;
		return *this;
	}
	
	OStream& OStream::operator<<(const char *cp)
	{
		write(cp);
		return *this;
	}
	
	OStream& OStream::operator<<(char c)
	{
		put(c) ;
		return *this;
	}
	
	OStream& OStream::operator<<(unsigned char *cq)
	{
		write((char *)cq) ;
		return *this;
	}
	
	OStream& OStream::operator<<(unsigned char c1)
	{
		put((char)c1) ;
		return *this;
	}
	
	OStream& OStream::operator<<(int n)
	{
		char* string = '\0';
		itoa(string,'x',n);
		cout << string;
		return *this;
	}
	
	OStream& OStream::operator<<(unsigned int n)
	{
		char *string = '\0';
		itoa(string,'x',n);
		cout << string;
		return *this;
	}
	
	OStream& OStream::operator<<(long l)
	{
		char *string = '\0';
		itoa(string,'x',(int) l);
		cout << string;
		return *this;
	}
	
	OStream& OStream::operator<<(string str)
	{
		for (int i=0;i<str.size();i++)
		{
			cout << str[i];
		}
		return *this;
	}
	
	OStream& OStream::operator<<(unsigned long l)
	{
		char *string = '\0';
		itoa(string,'x',(int) l);
		cout << string;
		return *this;
	}
		
	OStreamError& OStreamError::operator<<(char *cp)
	{
		cout << cp;
		error = true;
		return *this;
	}
	
	OStreamError& OStreamError::operator<<(const char *cp)
	{
		cout << cp;
		error = true;
		return *this;
	}
	
	OStreamError& OStreamError::operator<<(char c)
	{
		cout << c;
		error = true;
		return *this;
	}
	
	OStreamError& OStreamError::operator<<(unsigned char *cq)
	{
		cout << cq;
		error = true;
		return *this;
	}
	
	OStreamError& OStreamError::operator<<(unsigned char c1)
	{
		cout << c1;
		error = true;
		return *this;
	}
	
	OStreamError& OStreamError::operator<<(int n)
	{
		cout << n;
		error = true;
		return *this;
	}
	
	OStreamError& OStreamError::operator<<(unsigned int n)
	{
		cout << n;
		error = true;
		return *this;
	}
	
	OStreamError& OStreamError::operator<<(long l)
	{
		cout << l;
		error = true;
		return *this;
	}
	
	OStreamError& OStreamError::operator<<(unsigned long l)
	{
		cout << l;
		error = true;
		return *this;
	}
	
	void
	itoa (char *buf, int base, int d)
	{
		char *p = buf;
		char *p1, *p2;
		unsigned long ud = d;
		int divisor = 10;
		
		/* If %d is specified and D is minus, put `-' in the head. */
		if (base == 'd' && d < 0)
		{
			*p++ = '-';
			buf++;
			ud = -d;
		}
		else if (base == 'x')
			divisor = 16;
		
		/* Divide UD by DIVISOR until UD == 0. */
		do
		{
			int remainder = ud % divisor;
			
			*p++ = (remainder < 10) ? remainder + '0' : remainder + 'a' - 10;
		}
		while (ud /= divisor);
		
		/* Terminate BUF. */
		*p = 0;
		
		/* Reverse BUF. */
		p1 = buf;
		p2 = p - 1;
		while (p1 < p2)
		{
			char tmp = *p1;
			*p1 = *p2;
			*p2 = tmp;
			p1++;
			p2--;
		}
	}	
}

